package com.mukefile.service.impl;

import com.mukefile.dao.ManagerDao;
import com.mukefile.pojo.Manager;
import com.mukefile.pojo.User;
import com.mukefile.service.ManagerService;
import com.mukefile.utils.GenerateDiskRootPath;
import com.mukefile.utils.GetPathProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: kenewstar
 * @Description:
 * @Date:Created in 2020/5/6
 */
@Service("managerService")
@Transactional(rollbackFor = Exception.class)
public class ManagerServiceImpl implements ManagerService {

    @Autowired
    private ManagerDao managerDao;
    @Autowired
    private GetPathProperties getPathProperties;

    @Override
    public Manager managerLogin(Manager manager) {
        return this.managerDao.selectManagerInfo(manager);
    }

    @Override
    public void managerExit(Map<String, Object> session) {
        session.remove("manager");
    }

    @Override
    public List<User> showAllUser() {
        List<User> users = this.managerDao.showAllUser();
        return users;
    }

    @Override
    public int resetPwd(Integer uid,Manager manager) {
        int i = this.managerDao.updateUserPwd(uid);
        if (i==0){  //失败
            return 0;
        }
        //成功
        return 1;
    }

    @Override
    public int expandDisk(Integer uid, Integer size,Manager manager) {
        int i = this.managerDao.updateDiskAvail(uid, size);
        if (i==0){
            return 0;
        }
        return 1;
    }

    @Override
    public List<User> searchUser(String username) {
        List<User> users = this.managerDao.selectUserByLike(username);
        return users;
    }

    @Override
    public List<User> selectUserByName(String username) {
        List<User> users = this.managerDao.selectUserByName(username);
        return users;
    }

    @Override
    public int addUser(User user,Manager manager) {
        //查询数据库最后一条用户
        User lastUser = this.managerDao.getLastUser();
        user.setDiskRootPath(GenerateDiskRootPath.GenerateDRP(lastUser.getId()+1));
        int i = this.managerDao.insertUser(user);
        String diskRootPath = getPathProperties.getDiskRootPath()+
                File.separator+user.getDiskRootPath();
        File file = new File(diskRootPath);
        if (i==0){
            return 0;
        }
        if (file.exists()){
            //目录存在,返回成功
            return 1;
        }else {//不存在，创建目录
            boolean mkdir = file.mkdir();
            if (mkdir) {
                //成功
                return 1;
            }else {
                return 0;
            }
        }
    }
}
